interface ViewportDirectiveBinding {
  callback: () => void;
  once?: boolean;
  threshold?: number;
}

// 用来监听元素是否出现在视口
export const viewportDirective = {
  mounted(el: HTMLElement, binding: { value: ViewportDirectiveBinding }) {
    const { callback, once = true, threshold = 0.1 } = binding.value;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            callback();
            if (once) {
              observer.unobserve(el);
            }
          }
        });
      },
      {
        threshold // 使用传入的阈值
      }
    );

    observer.observe(el);
  }
};
